//各界面跳转
$('footer>div').on('click', function () {
    $(this).addClass('active').siblings().removeClass('active')
})
$('.index1').on('click', function () {
    location.href = '../pages/index.html'
})
$('.mian1').on('click', function () {
    
    location.href = '../pages/mian.html'
})
$('.cart1').on('click', function () {
    location.href = '../pages/cart.html'
})
$('.login1').on('click', function () {
    location.href = '../pages/login.html'
})
let productList ={}
//获取商品列表数据

let productListStr = '' //所有商品列表字符
//获取商品列表数据
function getProductList(categoryId, pageNo) {
    $.ajax({
        url: 'http://api.yuguoxy.com/api/shop/list/category',
        type: 'get',
        data: {
          categoryId,
            pageNo,
            pageSize: 14
        },
        success: function (data) {
            if (data.resultCode == 1) {
                let product = data.resultInfo.list
                    productList =product
                loadProductList(product)
            }
        }
    })
}

/**
 * 动态渲染商品列表
 * @param {}} productList 
 */
function loadProductList(productList) {
    let arr = productList.map(item => {
        return `<div class="item">
                   <img src="${item.picture}" alt="">
                   <div class="item-r">
                   <p class="p1">${item.product}</p>
                   <span>￥${item.price}</span>
                   <p class="p2" data-id="${item.id}">加入购物车</p>
                    </div>
                    </div>`
    })
    let str = arr.join('')
    productListStr =   str
    $('.con-r').html(productListStr)
    onProductCart()
    
}
 

//点击p切换分类
let pEle = document.querySelectorAll('.con-l>p')
for (let i = 0; i < pEle.length; i++) {
    pEle[i].addEventListener('click', function () {
        let hh=i+1
        getProductList(hh, 1)
    })
}


/*
 *加入购物车
*/ 
function onProductCart() {
    $('.p2').unbind().on('click', function () {
        //1. 先从localStorage取数据
        let cartStr = localStorage.getItem('Y-CART')
        let cartList = JSON.parse(cartStr) || []
 
        //2.选中商品
        let id = $(this).attr('data-id')
        //3.根据选中的商品ID获取购物车中商品
        let cartProduct = cartList.find(item => item.id == id)
        //3.1判断商品购物车中是否已经存在
        if (cartProduct) {
            cartProduct.num++
            
        } else {
            let product = productList.find(item => item.id == id)
            let newProduct = {
                id:product.id,
                num: 1,
                price: product.price,
                url: product.picture,
                product: product.product,
                singlePrice: product.price,
                state: false,
            } 
            cartList.push(newProduct)
        }
        //4.持久化存到localStorage
        localStorage.setItem('Y-CART', JSON.stringify(cartList))
        alert('加入购物车成功!')

    })
}


getProductList(1, 1)